package com.zsinfo.guoss.supplier.fragment.PaySetting;


import android.content.Intent;
import android.graphics.Color;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


import com.example.netcenter.Event.Response;
import com.example.netcenter.NetCenter;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.google.gson.Gson;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.activity.PaySettingsActivity;
import com.zsinfo.guoss.supplier.customize.Keyboard;
import com.zsinfo.guoss.supplier.customize.PayEditText;
import com.zsinfo.guoss.supplier.utils.CommentUtil;
import com.zsinfo.guoss.supplier.utils.Md5util;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

import java.util.HashMap;
import java.util.Map;

import static com.zsinfo.guoss.supplier.utils.CommentUtil.showSingleToast;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_PwdSettings extends Fragment {

    private PaySettingsActivity paySettingsActivity;
    private TextView tv_forget;

    //键
    private static final String[] KEY = new String[]{
            "1", "2", "3",
            "4", "5", "6",
            "7", "8", "9",
            "<<", "0", "完成"
    };


    PayEditText payEditText;
    Keyboard keyboard;
    private int time = 0;

    private Button btn_complete;

    private StringBuffer password1;

    private StringBuffer password2;

    private StringBuffer password0;

    private TextView tv_cash_tip;


    public Fragment_PwdSettings() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fragment__pwd_settings, container, false);

        keyboard = (Keyboard) view.findViewById(R.id.Keyboard_pay);

        payEditText = (PayEditText) view.findViewById(R.id.PayEditText_pay);

        tv_cash_tip = (TextView) view.findViewById(R.id.tv_cash_tip);

        tv_forget = (TextView) view.findViewById(R.id.tv_forget);

        paySettingsActivity = (PaySettingsActivity) getActivity();

        btn_complete = (Button) view.findViewById(R.id.btn_complete);

        btn_complete.setVisibility(View.GONE);

        btn_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        tv_forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                paySettingsActivity.switchFragment("Fragment_Validate");

            }
        });

        init();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        time = paySettingsActivity.setFlag;

        if (time == 1) {
            tv_cash_tip.setText("请输入6位数密码");
            tv_forget.setVisibility(View.GONE);
        } else {
            tv_cash_tip.setText("请输入旧密码");
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


    private void init() {

        keyboard.setKeyboardKeys(KEY);

        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {

                if (position < 11 && position != 9) {

                    payEditText.add(value);

                } else if (position == 9) {

                    payEditText.remove();

                } else if (position == 11) {

                    //当点击d键盘上的完成时候，也可以通过payEditText.getText()获取密码，此时不应该注册OnInputFinishedListener接口
                    String password = payEditText.getText();

                    if (TextUtils.isEmpty(password)) {
                        CommentUtil.showSingleToast("请输入密码");
                        return;
                    }
                    if (password.length() < 6) {

                        CommentUtil.showSingleToast("密码不能少于6位");

                        return;
                    }

                    onFinishSetPwd();
                }
            }
        });

        //当密码输入完成时的回调
        payEditText.setOnInputFinishedListener(new PayEditText.OnInputFinishedListener() {
            @Override
            public void onInputFinished(String password) {

                if (TextUtils.isEmpty(password)) {
                    CommentUtil.showSingleToast("请输入6位提现密码");
                    return;
                }

                if (password.length() < 6) {
                    CommentUtil.showSingleToast("密码少于6位");
                    return;
                }

                onFinishSetPwd();
            }
        });
    }

    /**
     * 清空密码
     */
    private void clearPassword() {
        for (int i = 0; i < 6; i++) {
            payEditText.remove();
        }
    }


    private void setCashPwd() {


        String oldP = "";

        if (password0 != null && !password0.toString().isEmpty()) {

            oldP = password0.toString();

        }


        new NetCenter().GetNetCenter(RetrofitBuilder.CreateApi().SET_PASSWORD(ConstantsCode.set_password,
                SharedPreferencesUtil.getID(),
                paySettingsActivity.SMSCode,
                Md5util.GetMD5Code(oldP),
                Md5util.GetMD5Code(password1.toString()),
                Md5util.GetMD5Code(password2.toString())), new Response() {
            @Override
            public void OK(Object data) {
                showSingleToast("密码设置成功!");
                paySettingsActivity.finish();
            }

            @Override
            public void Fail(Throwable e) {
                if (!e.getLocalizedMessage().contains("100000") && e.getLocalizedMessage().contains("Code")) {
                    ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                    showSingleToast(errorBean.getMsg());
                }
            }

            @Override
            public void complete() {


            }
        });


    }

    private void onFinishSetPwd() {
        if (time == 0) {
            password0 = new StringBuffer(payEditText.getText());
            oldPwd();
            return;
        }
        if (time == 1) {

            password1 = new StringBuffer(payEditText.getText());
            tv_cash_tip.setText("请再次输入密码");
            time = 2;
            clearPassword();
            return;
        }


        if (time == 2) {

            password2 = new StringBuffer(payEditText.getText());
            Log.e("Conker", password1.toString() + "," + password2.toString());
            if (TextUtils.equals(password1.toString(), password2.toString())) {
                //   设置成功
                setCashPwd();

            } else {
                //    设置失败，重新设置
                clearPassword();
                tv_cash_tip.setTextColor(Color.RED);
                tv_cash_tip.setText("密码不一致,请重新输入密码");

            }

        }
    }

    private void oldPwd() {

        if (password0.toString().isEmpty()) {
            CommentUtil.showSingleToast("密码为空 ");
            return;
        }


        new NetCenter().GetNetCenter(getContext(), RetrofitBuilder.CreateApi().SET_PASSWORD(ConstantsCode.set_password,
                SharedPreferencesUtil.getID(),
                "",
                Md5util.GetMD5Code(password0.toString()),
                "",
                ""), new Response() {
            @Override
            public void OK(Object data) {
                clearPassword();
                time = 1;
                tv_cash_tip.setText("请输入新密码");
                tv_forget.setVisibility(View.GONE);


            }

            @Override
            public void Fail(Throwable e) {
                if (!e.getLocalizedMessage().contains("100000") && e.getLocalizedMessage().contains("Code")) {
                    ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                    showSingleToast(errorBean.getMsg());
                }
                clearPassword();
                time = 0;
            }

            @Override
            public void complete() {


            }
        });


    }
}
